package ubi.quando.UI;

import java.util.Iterator;
import java.util.List;

import ubi.quando.App.EventBase;
import ubi.quando.App.EventPickUp;
import ubi.quando.App.EventType;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class MainMenu extends Activity {

	public static final int CHOOSE_EVENT_DIALOG = 0;

	UbiApplication mApp;

	private TableLayout mEvents;
	private Button mBtnNewEvent;
	private Button mBtnAbout;
	private Button mBtnExit;
	private Button mBtnAddContact;
	private EditText mTxtContactMail;
	private TextView mTvEmail;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mApp = (UbiApplication) getApplication();
		mApp.setCurrentActivity(this);

		if (!NotificationManager.IS_RUNNING) {
			startService(new Intent(MainMenu.this, NotificationManager.class));
		}

		mEvents = (TableLayout) findViewById(R.id.tl_events);
		mTxtContactMail = (EditText) findViewById(R.id.txt_contactMail);
		mBtnNewEvent = (Button) findViewById(R.id.btn_newEvent);
		mBtnAbout = (Button) findViewById(R.id.btn_about);
		mBtnExit = (Button) findViewById(R.id.btn_exit);
		mBtnAddContact = (Button) findViewById(R.id.btn_addContact);
		mTvEmail = (TextView) findViewById(R.id.tv_email);

		initFont();
	}

	private void initFont() {
		Typeface font = Typeface.createFromAsset(getAssets(), "AGENCYR.TTF");

		mBtnNewEvent.setTypeface(font);
		mBtnAbout.setTypeface(font);
		mBtnExit.setTypeface(font);
		mBtnAddContact.setTypeface(font);
		mTxtContactMail.setTypeface(font);
		mTvEmail.setTypeface(font);
	}

	@Override
	protected void onResume() {
		super.onResume();
		mApp.setCurrentActivity(this);

		mEvents.removeAllViews();

		AddTableTitle();

		List<EventBase> events = mApp.getEvents();
		if (events.size() == 0) {
			AddNoEventsText();
		} else {
			AddEventsToTable(events);
		}
	}

	private void AddEventsToTable(List<EventBase> events) {
		Iterator<EventBase> iter = events.iterator();
		while (iter.hasNext()) {
			Typeface font = Typeface
					.createFromAsset(getAssets(), "AGENCYR.TTF");
			EventBase next = iter.next();
			TableRow row = new TableRow(this);
			row.setTag(next.getId());
			TextView name = new TextView(this);
			name.setText(next.GetName());
			name.setTextColor(ColorStateList.valueOf(-7829368));
			name.setGravity(Gravity.CENTER);
			name.setTextSize(20);
			name.setTypeface(font);
			// name.setTextColor(Color.rgb(52, 2, 153));
			Button startEvent = new Button(this);
			startEvent.setText("Start");
			startEvent.setGravity(Gravity.CENTER);
			startEvent.setTypeface(font);
			startEvent.setBackgroundResource(R.drawable.my_button);
			startEvent.setTextSize(20);
			startEvent.setWidth(100);
			startEvent.setTextColor(Color.rgb(52, 2, 153));
			startEvent.setOnClickListener(new StartOnClickListener());
			if (!(next.getCreatorId().equals(mApp.getId()))) {
				startEvent.setEnabled(false);
			}
			Button detailsEvent = new Button(this);
			detailsEvent.setText("Details");
			detailsEvent.setGravity(Gravity.CENTER);
			detailsEvent.setOnClickListener(new DetailsOnClickListener());
			detailsEvent.setTypeface(font);
			detailsEvent.setTextSize(20);
			detailsEvent.setWidth(100);
			detailsEvent.setTextColor(Color.rgb(52, 2, 153));
			detailsEvent.setBackgroundResource(R.drawable.my_button);
			if (!(next.getCreatorId().equals(mApp.getId()))) {
				detailsEvent.setEnabled(false);
			}
			// row.addView(image);
			row.addView(name);
			row.addView(detailsEvent);
			row.addView(startEvent);
			mEvents.addView(row);
		}
	}

	private void AddNoEventsText() {
		TableRow row = new TableRow(this);
		TextView tableName = new TextView(this);
		tableName.setText("You have no event in your account");
		tableName.setTextColor(ColorStateList.valueOf(-7829368));
		row.addView(tableName);
		mEvents.addView(row);
	}

	private void AddTableTitle() {
		TableRow row = new TableRow(this);
		TextView tableName = new TextView(this);
		tableName.setText("My Events:");
		tableName.setTextColor(ColorStateList.valueOf(-7829368));
		row.addView(tableName);
		mEvents.addView(row);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case CHOOSE_EVENT_DIALOG:
			Resources res = getResources();
			String[] items = { String.format(res.getString(R.string.meeting)),
					String.format(res.getString(R.string.i_pick_u)),
					String.format(res.getString(R.string.pick_me_up)) };

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Event Type");
			builder.setItems(items, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					createNewEvent(item);
				}
			});
			AlertDialog alertDialog = builder.create();
			return alertDialog;
		}
		return null;
	}

	private void createNewEvent(int eventType) {
		EventType type = EventType.FromInt(eventType);
		Intent intent = null;
		switch (type) {
		case MEETING:
			intent = new Intent(getApplicationContext(),
					ArrangeMeetingActivity.class);
			startActivity(intent);
			break;
		case I_PICK_U:
			intent = new Intent(getApplicationContext(),
					ArrangeIPickUActivity.class);
			startActivity(intent);
			break;
		case PICK_ME_UP:
			intent = new Intent(getApplicationContext(),
					ArrangePickMeUpActivity.class);
			startActivity(intent);
			break;
		}
	}

	public void onNewEvent(View view) {
		showDialog(CHOOSE_EVENT_DIALOG);
	}

	public void onExit(View view) {
		onDestroy();
	}

	@Override
	protected void onDestroy() {
		stopService(new Intent(MainMenu.this, NotificationManager.class));
		super.onDestroy();
		System.exit(0);
	}

	public void onAbout(View view) {
		setContentView(R.layout.about_layout);
	}

	public void onSearch(View view) {
		String contactMail = mTxtContactMail.getText().toString();

		if (mApp.getServerComm().friendRequest(contactMail)) {
			Log.i("Super", "Friend request sent");
		}
		
		mTxtContactMail.setText("");
	}

	public class StartOnClickListener implements OnClickListener {

		public void onClick(View v) {
			TableRow row = (TableRow) v.getParent();
			EventBase event = mApp.getEventById((String) row.getTag());

			mApp.getServerComm().startEvent(
					event.getId(),
					(event.getType() == EventType.PICK_ME_UP) ? EventType
							.ToInt(EventType.I_PICK_U) : EventType.ToInt(event
							.getType()));
			// TODO: maybe should wait for the server to send stard notification
			mApp.HandleEventStarted(event.getId());
		}
	}

	public class DetailsOnClickListener implements OnClickListener {

		public void onClick(View v) {
			// TODO: choose which activities to call
			TableRow row = (TableRow) v.getParent();
			EventBase event = mApp.getEventById((String) row.getTag());

			Intent eventDetails;
			if (event.getType() == EventType.MEETING) {
				eventDetails = new Intent(v.getContext(),
						ArrangeMeetingActivity.class);
			} else {
				EventPickUp pickUp = (EventPickUp) event;
				if (pickUp.getPickerId().equals(mApp.getId())) {
					eventDetails = new Intent(v.getContext(),
							ArrangeIPickUActivity.class);
				} else {
					eventDetails = new Intent(v.getContext(),
							ArrangeIPickUActivity.class);
				}
			}

			Bundle b = new Bundle();
			b.putSerializable(EventBase.SerializeName, event);

			eventDetails.putExtras(b);
			// startActivity(eventDetails);
		}

	}

}